<?php
/**
 * Created by PhpStorm.
 * User: MrHung
 * Date: 5/12/14
 * Time: 9:42 AM
 */

namespace Admin\Controller;


use Zend\Mvc\Controller\AbstractActionController;
use Admin\Model\AdminPage;
use Velacolib\Utility\Utility;
use Zend\View\Model\ViewModel;

class PageController extends AbstractActionController
{

    private $pageTable;

    public function onDispatch(\Zend\Mvc\MvcEvent $e)
    {
        $this->pageTable = Utility::UserGateway('Admin\Model\AdminPageTable');
        return parent::onDispatch($e);
    }
    public function init()
    {

    }


    public function indexAction()
    {
        $page = $this->pageTable->fetchAll(null,$order = 'page_date ASC');
        return new ViewModel(array(
            'page'=>$page,
        ));
    }


    public function addAction()
    {


        if ($this->getRequest()->isPost()) {
            $page_data = $this->params()->fromPost();
            $page_data['page_date'] = time();
            $page_data['slug'] = Utility::alphabetconvert($page_data['title']).'-'.time();
            $page_model = new AdminPage();

            $page_model->exchangeArray($page_data);

            $this->pageTable->savePage($page_model);

        }
        $page_parent = $this->pageTable->fetchAll();
        return new ViewModel(array(
            'page_parent'=>$page_parent

        ));


    }

    /**
     * @return ViewModel
     */
    public function editAction()
    {

        if ($this->getRequest()->isPost()) {
            $page_data = $this->params()->fromPost();
            $page_data['page_date'] = time();
            $page_data['slug'] = Utility::alphabetconvert($page_data['title']).'-'.time();
            $page_model = new AdminPage();

            $page_model->exchangeArray($page_data);

            $this->pageTable->savePage($page_model);


            $pageId = $page_data['id'];
            $page = $this->pageTable->getPage($pageId);
            $page_parent = $this->pageTable->fetchAll();
            return new ViewModel(array(
                'page'=>$page,
                'page_parent'=>$page_parent

            ));
        }

            $pageId = $this->params()->fromRoute('id');
            $page = $this->pageTable->getPage($pageId);
            $page_parent = $this->pageTable->fetchAll();
            return new ViewModel(array(
                'page'=>$page,
                'page_parent'=>$page_parent

            ));
    }

    /**
     *
     */
    public function deleteAction()
    {

            $id = $this->params()->fromRoute('id');

           $this->pageTable->deletePage($id);
            $this->redirect()->toRoute('admin/child', array('controller'=>'page'));

    }

} 